package name.zeno.qrcode;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import java.io.File;

import name.zeno.qrcode.library.QRCodeUtil;

/**
 * 二维码生成
 */
public class MainActivity extends Activity
{
    EditText contentET;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //内容
contentET = (EditText) findViewById(R.id.et_content);
        //显示二维码图片
        final ImageView imageView   = (ImageView) findViewById(R.id.iv_qrcode);
        Button          createQrBtn = (Button) findViewById(R.id.btn_generate);

        createQrBtn.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                final String filePath = getFileRoot(MainActivity.this) + File.separator
                        + "qr_" + System.currentTimeMillis() + ".jpg";

                boolean success = QRCodeUtil.createQRImage(contentET.getText().toString().trim(),
                        344, 344,
                        BitmapFactory.decodeResource(getResources(), R.drawable.avatar), filePath);
                if (success)
                    imageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
            }
        });

        Button readBtn = (Button) findViewById(R.id.btn_read);
        readBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent(MainActivity.this, QRCodeReaderActivity.class);
                startActivityForResult(intent, 1);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        String result = data.getStringExtra("result");
        if (result != null) {
            contentET.setText("扫描结果: "+result);
        }

    }

    //文件存储根目录
    private String getFileRoot(Context context)
    {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }

        return context.getFilesDir().getAbsolutePath();
    }
}
